/*
 * TempSensor.java
 *
 * By Gary Wong, 2005.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of Version 2 of the GNU General Public 
 * License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package sxe.sensors;

import snobject.snObject;
import snobject.snString;

public class TempSensor extends GenericSensor {
    protected BaseStation baseStation;
    protected int id; /* network address of the sensor -- unrelated to
			 the SXE node ID */
    protected String location;

    
	/** no one should call this constructor other than the Parser for use by the SSD/SRM!! */
	protected TempSensor(){
		super();
	}

	
    public TempSensor( BaseStation baseStation, int id, String location ) {
		//super();
    	m_state = GenericSensor.STATE_PREINIT;
		m_type = TYPE_TEMPERATURE;
		this.baseStation = baseStation;
		this.id = id;
		this.location = location;
		super.m_uri = m_type + "/" + m_id;
		SensorDetector.RegisterID(m_id);
    }

    /* return true if initialization has succeeded
     * false otherwise */
    public boolean initializeSensor() {
	m_state = STATE_INIT;
	return true;
    }

    /* return true if the sensor is still up
     * or can be reached */
    public boolean isAlive() {
	return baseStation.getAge( id ) < 60000000000L;
    }

    /* return a string(?)  with the current reading */
    public snObject getData( Object oParam ) {

	int value;

	if( ( value = baseStation.getValue( id ) ) < 0 )
	    return new snString( "unknown" );

	double r = ( 1023 * 10000.0 / value ) - 10000; /* resistance in Ohms */
	double temp = 1 / ( 0.000231 * Math.log( r ) + 0.001225 ); /* temp K */

	return new snString( String.format( "%.1f", temp ) );
    }

    public boolean shutDown() {
	m_state = STATE_PREINIT;
	return true;
    }

    /* return an XML structured string with
     * static characteristics.  For a temp sensor I'm
     * thinking physical location, sampling rate,
     * units?  */
    public String GetInfoXML() {
	
    String b = "  <location>" + location + "</location>\n";
	b += "  <name>" + id + "</name>\n";
	b += "  <deviceFormats>\n" +
	    "    <tempFormat><unit>kelvin</unit></tempFormat>\n" +
	    "  </deviceFormats>\n";
	
	return super.GetInfoXML(b);
    }

}
